<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="冷库名称" prop="coldName">
        <el-input
          v-model="queryParams.coldName"
          placeholder="请输入冷库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="冷库描述" prop="coldDescript">
        <el-input
          v-model="queryParams.coldDescript"
          placeholder="请输入冷库描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="冷库地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入冷库地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最小面积" prop="area1">
        <el-input
          v-model="queryParams.area1"
          placeholder="请输入最小占地面积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最大面积" prop="area2">
        <el-input
          v-model="queryParams.area2"
          placeholder="请输入最大占地面积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最小容积" prop="totalVolume1">
        <el-input
          v-model="queryParams.totalVolume1"
          placeholder="请输入最小容积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最大容积" prop="totalVolume2">
        <el-input
          v-model="queryParams.totalVolume2"
          placeholder="请输入最大容积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="负责人" prop="managerId">-->
<!--        <el-select v-model="queryParams.managerId">-->
<!--          <el-option-->
<!--            v-for="user in storageUserList"-->
<!--            :key="user.userId"-->
<!--            :label="user.userName"-->
<!--            :value="user.userId">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="冷库状态" clearable>
          <el-option
            v-for="dict in dict.type.lg_storage_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['storage:bigCold:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:bigCold:update']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storage:bigCold:delete']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:bigCold:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" width="80">
        <template slot-scope="scope">
          {{ (scope.$index + 1) + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </el-table-column>
      <el-table-column label="冷库id" align="center" prop="coldId" />
      <el-table-column label="冷库名称" align="center" prop="coldName">
        <template slot-scope="scope">
          <el-button type="text" @click="getMap(scope.row)">{{ scope.row.coldName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="冷库地址" align="center" prop="address" />
      <el-table-column label="占地面积" align="center" prop="area">
        <template slot-scope="scope">
          {{ scope.row.area }} 平方米
        </template>
      </el-table-column>
      <el-table-column label="总容积" align="center" prop="totalVolume">
        <template slot-scope="scope">
          {{ scope.row.totalVolume }} 立方米
        </template>
      </el-table-column>
<!--      <el-table-column label="负责人id" align="center" prop="managerId" />-->
      <el-table-column label="负责人姓名" align="center" prop="managerName" />
<!--      <el-table-column label="负责人" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          {{ this.storageUserList.find(item => item.id === this.scope.row.managerId).userName}}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_storage_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['storage:bigCold:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['storage:bigCold:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTotalSome"
    />

    <!-- 添加或修改冷库 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="width: 500px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="冷库名称" prop="coldName">
            <el-input v-model="form.coldName" placeholder="请输入冷库名称" />
          </el-form-item>
          <el-form-item label="冷库描述" prop="coldDescript">
            <el-input v-model="form.coldDescript" placeholder="请输入冷库描述" />
          </el-form-item>
          <el-form-item label="冷库地址" prop="address">
            <el-input v-model="form.address"  placeholder="请输入冷库地址" />
          </el-form-item>
          <el-form-item label="经纬度X坐标" prop="coordinateX">
            <el-input v-model="form.coordinateX"  placeholder="请输入冷库经纬度X坐标" readonly/>
          </el-form-item>
          <el-form-item label="经纬度Y坐标" prop="coordinateY">
            <el-input v-model="form.coordinateY"  placeholder="请输入冷库经纬度Y坐标" readonly/>
          </el-form-item>
          <el-form-item label="占地面积" prop="area">
            <el-input v-model="form.area"  placeholder="请输入冷库占地面积"  />
          </el-form-item>
          <el-form-item label="总容积" prop="totalVolume">
            <el-input v-model="form.totalVolume"  placeholder="请输入冷库总容积"  />
          </el-form-item>
          <el-form-item label="负责人" prop="managerId">
            <el-select v-model="form.managerId" placeholder="请选择冷库负责人">
              <el-option
                v-for="user in storageUserList"
                :key="user.userId"
                :label="user.userName"
                :value="user.userId">
              </el-option>
            </el-select>
            <el-button  id = "openSome" @click="getSome">
              选择
            </el-button>
          </el-form-item>
          <el-form-item label="冷库状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.lg_storage_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="padding-left: 330px;padding-right: 0">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
      <!--放地图的div-->
      <div style="width: 450px;height: 600px; position: absolute;top:60px;left: 530px;">
        <baidu-map
          class="map"
          :center="{ lng: 113.65, lat: 34.76 }"
          :zoom="15"
          :scroll-wheel-zoom="true"
          mapType="BMAP_NORMAL_MAP"
          @click="handleMapClick"
        >
          <!-- 添加地图控件 -->
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <bm-scale anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-scale>
          <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>

          <!-- 添加定位控件 -->
          <bm-geolocation
            anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
            :showAddressBar="true"
            :autoLocation="true"
          ></bm-geolocation>

          <!-- 添加路况图层 -->
          <bm-traffic :type="0"></bm-traffic>

          <!-- 添加卫星图层（可选） -->
          <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-overview-map>
          <!-- 添加逆地理编码服务 -->
          <bm-geocoder
            :location="{ lng: mapX, lat: mapY }"
            :autoLocation="true"
            @locationSuccess="handleLocationSuccess"
          ></bm-geocoder>
          <!-- 添加标记 -->
          <bm-marker
            :position="{ lng: mapX, lat: mapY }"
          ></bm-marker>
        </baidu-map>
      </div>
    </el-dialog>
    <!-- 弹出框 -->
    <el-dialog :title="title2" :visible.sync="open3" width="1000px" append-to-body>
      <el-table :data="storageUserList" style="width: 100%">
        <el-table-column label="编号" align="center" width="80">
          <template slot-scope="scope">
            {{ (scope.$index + 1) + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="负责人ID" align="center"></el-table-column>
        <el-table-column prop="userName" label="负责人姓名" align="center"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="thisOk(scope.row)"
              v-hasPermi="['system:post:remove']"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelection">确认</el-button>
        <el-button @click="cancelSelection">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open2" width="1000px"  append-to-body>
      <baidu-map
        class="map2"
        :center="{ lng: mapX, lat: mapY }"
        :zoom="15"
        :scroll-wheel-zoom="true"
        mapType="BMAP_NORMAL_MAP"

      >
        <!-- 添加地图控件 -->
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        <bm-scale anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-scale>
        <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>

        <!-- 添加定位控件 -->
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
        ></bm-geolocation>

        <!-- 添加路况图层 -->
        <bm-traffic :type="0"></bm-traffic>

        <!-- 添加卫星图层（可选） -->
        <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-overview-map>
        <!-- 添加标记 -->
        <bm-marker
          :position="{ lng: mapX, lat: mapY }"
        ></bm-marker>
      </baidu-map>
      <div slot="footer" class="dialog-footer" style="padding-left: 330px;padding-right: 0">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import {getAll,getBigColdById,addBigCold,updateBigCold,getStorageUserList,getTotal, listPost,deleteBigCold, getPost, delPost,
  addPost, updatePost } from "@/api/storage/bigCold";
import store from "@/store";
export default {
  name: "Post",
  dicts: ['sys_normal_disable','lg_storage_status'],
  data() {
    return {
      clickedLocation: null, // 用于存储点击位置的经纬度
      userId:store.state.user.id, //将缓存的用户id赋值给userId
      userName:store.state.user.name, //将缓存的用户id赋值给userId
      // 遮罩层
      loading: true,
      //默认状态
      nowStatus: "1",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 大冷库表格数据
      storageList: [],
      // 冷库管理员名单
      storageUserList: [],
      // 弹出层标题
      title: "",
      title2: "选择负责人",
      // 是否显示弹出层
      open: false,
      open2: false,
      open3: false,
      // 弹出的地图的经纬度
      mapX: undefined,
      mapY: undefined,
      //获得的数据
      nowManager: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        coldName: undefined,
        coldDescript: undefined,
        address: undefined,
        area1: undefined,
        area2: undefined,
        totalVolume1: undefined,
        totalVolume2: undefined,
        managerId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        coldName: [
          { required: true, message: "冷库名称不能为空", trigger: "blur" }
        ],
        coldDescript: [
          { required: true, message: "冷库描述不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址不能为空,点击右侧地图以添加", trigger: "blur" }
        ],
        coordinateX: [
          { required: true, message: "经度不能为空，点击右侧地图以添加", trigger: "blur" }
        ],
        coordinateY: [
          { required: true, message: "纬度不能为空", trigger: "blur" }
        ],
        area: [
          { required: true, message: "占地面积不能为空", trigger: "blur" }
        ],
        totalVolume: [
          { required: true, message: "总容积不能为空", trigger: "blur" }
        ],
        managerId: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // this.getList();
    // this.getStorage();
    this.getTotalSome();
    this.getStorageUserListSome();
  },
  methods: {
    thisOk(some){
      this.nowManager = some;
      this.form.managerId = some.userId;
      console.log(some.userName);
    },
    cancelSelection(){
      this.open3 = false;
    },
    confirmSelection(){
      this.form.managerId = this.nowManager.userId;
      this.open3 = false;
    },
    //弹出页面
    getSome(){
      this.open3 = true;
    },
    //获得负责人名字
    getManagerName(){
      console.log(this.storageUserList);
    },
    //点击冷库名字弹出地图
    getMap(some){
      this.open2 = true;
      this.mapX = some.coordinateX;
      this.mapY = some.coordinateY;
      console.log(this.mapX);
    },
    //获取点击位置经纬度
    handleMapClick(e) {
      // 获取点击位置的经纬度
      const { lng, lat } = e.point;
      this.clickedLocation = { lng, lat };
      // console.log("点击位置的经度：", lng);
      // console.log("点击位置的纬度：", lat);
      this.form.coordinateX = lng;
      this.form.coordinateY = lat;
      this.mapX = this.form.coordinateX;
      this.mapY = this.form.coordinateY;
      // 调用逆地理编码服务
      this.getAddressFromCoordinates(lng, lat);
    },
    // 调用逆地理编码服务获取地址
    getAddressFromCoordinates(lng, lat) {
      const geocoder = new BMap.Geocoder();
      geocoder.getLocation(new BMap.Point(lng, lat), (result) => {
        if (result) {
          this.form.address = result.address;
        }
      });
    },

    // 逆地理编码服务成功回调
    handleLocationSuccess(result) {
      if (result) {
        this.form.address = result.address;
      }
    },
    /** 查询所有冷库 */
    getStorage() {
      getAll(this.queryParams).then(response => {
        this.storageList = response.data;
        // console.log(response);
        //将负责人姓名塞进去
        for (var i = 0; i < this.storageList.length; i++){
          for (var j = 0; j < this.storageUserList.length; j++){
            if (this.storageList[i].managerId == this.storageUserList[j].userId){
              this.storageList[i].managerName = this.storageUserList[j].userName;
              // console.log(this.storageList[i].managerName);
            }
          }
        }
      });
    },
    /** 查询冷库管理员名单 */
    getStorageUserListSome() {
      getStorageUserList().then(response => {
        this.storageUserList = response.data;
      });
      this.getStorage();
    },
    //获取数据总条数
    getTotalSome() {
      // console.log(this.queryParams);
      this.loading = true;
      getTotal(this.queryParams).then(response => {
        this.getStorage();
        this.total = response.data;
        // alert(this.total);
        // console.log(response);
        this.loading = false;
      });
    },
    //删除数据

    /** 查询岗位列表 */
    // getList() {
    //   this.loading = true;
    //   listPost(this.queryParams).then(response => {
    //     this.postList = response.rows;
    //     // this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        coldId: undefined,
        coldName: undefined,
        coldDescript: undefined,
        address: undefined,
        coordinateX: undefined, // 初始化经度
        coordinateY: undefined, // 初始化纬度
        area: undefined,
        totalVolume: undefined,
        managerId: undefined,
        status: "0",
        createBy: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTotalSome();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.coldId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.mapX = undefined;
      this.mapY = undefined;
      this.open = true;
      this.title = "添加冷库";
      this.form.status = this.nowStatus.toString();
      this.getStorageUserListSome();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getStorageUserListSome();
      // console.log(row);
      this.reset();
      const coldId = row.coldId || this.ids
      getBigColdById(coldId).then(response => {
        this.form = response.data;
        this.mapX = response.data.coordinateX;
        this.mapY = response.data.coordinateY;
        this.form.status= String(response.data.status);
        this.open = true;
        this.title = "修改冷库";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.coldId != undefined) {
            updateBigCold(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getStorage();
            });
          } else {
            //添加创建人
            this.form.createBy = this.userId;
            addBigCold(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getStorage();
              this.form = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const coldIds = row.coldId || this.ids;
      this.$modal.confirm('是否确认删除冷库数据项？').then(function() {
        return deleteBigCold(coldIds);
        // return delPost(coldIds);
      }).then(() => {
        this.getStorage();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/bigCold/export', {
        ...this.queryParams
      }, `bigCold_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.map {
  width: 100%;
  height: 100%;
}
.map2{
  width: 100%;
  height: 500px;
}
#openSome{
  margin-left: 20px;
  background-color: #BBFFFF;
}
#openSome:hover{
  background-color: #87CEEB; /* 更深的蓝色 */
  color: white; /* 鼠标悬停时字体颜色为白色 */
}
</style>
